package aaa.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class HashUtil {
    // 生成随机 SHA-256 哈希值的方法
    public static String generateRandomSha256Hash() throws NoSuchAlgorithmException {

        byte[] randomBytes = generateRandomBytes();

        // 创建 MessageDigest 实例，选择 SHA-256 算法
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        // 更新摘要
        digest.update(randomBytes);

        // 获取摘要的字节数组
        byte[] hashedBytes = digest.digest();

        // 将字节数组转换为十六进制字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (byte hashedByte : hashedBytes) {
            stringBuilder.append(Integer.toString((hashedByte & 0xff) + 0x100, 16).substring(1));
        }

        // 返回生成的 SHA-256 哈希值
        return stringBuilder.toString();
    }

    // 生成指定长度的随机字节数组
    private static byte[] generateRandomBytes() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] randomBytes = new byte[16]; // 16 bytes for SHA-256
        secureRandom.nextBytes(randomBytes);
        return randomBytes;
    }

}
